package ddns

import (
	"errors"
	"fmt"
	ali "gitee.com/goexc/ddns/service/alidns"
	"gitee.com/goexc/ddns/variables"
	"time"
)

type Client struct {
	Config
	QueryTicker   *time.Ticker //查询dns服务器的定时器
	PollingTicker *time.Ticker //轮询主机ip地址的定时器
}

type Config struct {
	QueryInterval   int    //查询dns服务器的时间间隔
	PollingInterval int    //轮询主机ip地址的时间间隔
	RegionId        string //区域
	AccessKeyId     string
	AccessKeySecret string
	Domains         string //域名列表：a.a.com, b.a.com, c.a.com
}

func NewClient(config Config) (*Client, error) {
	if config.QueryInterval <= 0 || config.PollingInterval <= 0 {
		return nil, errors.New("请设置时间间隔")
	}

	return &Client{
		Config:        config,
		QueryTicker:   time.NewTicker(time.Duration(config.QueryInterval) * time.Minute),
		PollingTicker: time.NewTicker(time.Duration(config.PollingInterval) * time.Minute),
	}, nil
}

func (c *Client) Run() error {
	s, e := ali.NewAliDnsService(c.Config.RegionId, c.Config.AccessKeyId, c.Config.AccessKeySecret)
	if e != nil {
		fmt.Println("AliDNS客户端创建失败", e)
		return e
	}

	//定时获取子域名解析记录列表
	//立即更新解析记录
	go func() {
		for {
			s.DescribeSubDomainRecords(c.Domains)
			<-c.QueryTicker.C
		}
	}()

	//TODO:消费过时消息
	go func() {
		ticker := time.NewTicker(5 * time.Second)
		for {
			if len(variables.Msg) >= cap(variables.Msg)/2 {
				for i := 0; i < cap(variables.Msg)/2; i++ {
					<-variables.Msg
				}
			}
			<-ticker.C
		}
	}()

	//定时修改解析记录
	for {
		s.UpdateDomainRecord()
		<-c.PollingTicker.C
	}
}
